package com.itbaizhan.myshiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itbaizhan.myshiro.domain.Admin;
import com.itbaizhan.myshiro.mapper.AdminMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

//在系统中有管理员和普通用户两张表，管理员和普通用户的认证逻辑是不一样的；
//这是管理员逻辑
public class MyRealm2 extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //自定义认证

    @Autowired
    private AdminMapper adminMapper;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取前端的用户名
        //把参数强转为userPasswordToken
        UsernamePasswordToken token1 = (UsernamePasswordToken)authenticationToken;
        String username = token1.getUsername();
        //根据用户名在数据库里查询用户
        QueryWrapper<Admin> wrapper = new QueryWrapper<Admin>().eq("name", username);
        Admin admin = adminMapper.selectOne(wrapper);
        //将查询到的用户封装为身份信息
        if(admin == null){
            throw  new UnknownAccountException("管理员不存在");
        }

        //参数1：查询到的用户  参数2：用户密码 参数3：加密算法的盐 参数4：realm名
        return new SimpleAuthenticationInfo(admin,
                admin.getPassword(),
                ByteSource.Util.bytes(admin.getSalt()),
                "MyRealm2");
    }
}
